package com.suemi.missile.common.mql.maker;

import com.google.common.collect.ImmutableSet;
import com.suemi.missile.common.mql.domain.Condition;
import com.suemi.missile.common.mql.exception.MqlParseException;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.index.query.QueryBuilders;

import java.util.Set;

public abstract class Maker {

  private static final Set<Condition.OPEAR> NOT_OPEAR_SET = ImmutableSet.of();

  protected Maker(Boolean isQuery) {

  }

  protected ToXContent make(Condition cond) throws MqlParseException {

    String name = cond.getName();
    Object value = cond.getValue();
    ToXContent x = null;
    x = make(cond, name, value);

    return x;
  }

  private ToXContent make(Condition cond,String name, Object value) throws MqlParseException {
    ToXContent x = null;
    switch (cond.getOpear()) {
      case LIKE:
        String queryStr = ((String) value);
        queryStr = queryStr.replace('%', '*').replace('_', '?');
        queryStr = queryStr.replace("&PERCENT","%").replace("&UNDERSCORE","_");
        x = name.toUpperCase().equals("ANY")?QueryBuilders.wildcardQuery("_all",queryStr):QueryBuilders.wildcardQuery(name, queryStr);
        break;
      case MATCH:
        String word = ((String) value);
        x = name.toUpperCase().equals("ANY")?QueryBuilders.matchQuery("_all",word):QueryBuilders.matchQuery(name,word);
        break;
      default:
        throw new MqlParseException("not define type " + cond.getName());
    }
    return x;
  }
}
